package com.gcd.commom;


import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gcd.utils.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入JwtInterceptor拦截器");
        System.out.println("请求方法: " + request.getMethod());
        System.out.println("请求URI: " + request.getRequestURI());

        // 对于OPTIONS请求直接放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            System.out.println("OPTIONS请求直接放行");
            return true;
        }

        String jwt = request.getHeader("Authorization");
        System.out.println("获取到的Authorization头: " + jwt);

        // 添加对空 JWT 的检查
        if (jwt == null || jwt.isEmpty()) {
            String message = "未提供认证信息";
            System.out.println("Authorization头为空或不存在");
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(JsonResult.fail(message)));
            out.flush();
            return false;
        }

        // 处理Bearer前缀
        if (jwt.startsWith("Bearer ")) {
            jwt = jwt.substring(7); // 去掉"Bearer "前缀
            System.out.println("处理后的JWT: " + jwt);
        }

        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(jwtSecret)).build();
        System.out.println("JWT Secret: " + jwtSecret);

        try {
            DecodedJWT dj = verifier.verify(jwt);
            System.out.println("JWT验证成功");
            Integer userId = dj.getClaim("userId").asInt();
            System.out.println("解析到的userId: " + userId);
            request.setAttribute("userId", userId);
            return true;
        } catch (JWTVerificationException e) {
            String message = "jwt无效或过期";
            System.out.println("JWT验证失败: " + e.getMessage());
            e.printStackTrace();
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(JsonResult.fail(message)));
            out.flush();
            return false;
        }
    }


}